#include<string>
#include<vector>
#include<array>
#include<unordered_map>
#include<algorithm>
#include<limits>
#include <stack>
#define MOD 1000000007
class Solution {
public:
    int sumSubarrayMins(std::vector<int>& arr) {
        std::stack<int> istack;
        int n = arr.size();
        std::vector<int> res(n);
        long long ans = 0;
        for (int i = 0; i < n; i++)
        {
            if (istack.empty()||arr[istack.top()]<arr[i])
            {
                istack.push(i);
                continue;
            }
            while (!istack.empty() && arr[istack.top()] >= arr[i])
            {
                int r = i;
                int index= istack.top();
                istack.pop();
                int l = istack.empty()?-1:istack.top();
                long long temp = arr[index];
                ans=(ans+temp*(index-l)*(r-index))%MOD;
            }
            istack.push(i);
        }
        while (!istack.empty())
        {
            int index = istack.top();
            istack.pop();
            int l = istack.empty()?-1:istack.top();
            long long temp = arr[index];
            ans=(ans+temp*(index-l)*(n-index))%MOD;
        }
        return (int)ans;
    }
};
